package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constrant.MessageConstant;
import com.itheima.constrant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @author FCJ
 * @date 2020-01-07 19:07
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Reference
    private OrderService orderService;
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/submit")
    public Result submitOrder(@RequestBody Map map) {
        String telephone = (String) map.get("telephone");
        //获取redis中的验证码
        String codeinRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        if (codeinRedis == null) {
            return new Result(false, "验证码已过期，请重新获取");
        }
        //获取手机中的验证码
        String validateCode = (String) map.get("validateCode");
        //判断验证码是否匹配
        if (validateCode == null || !codeinRedis.equals(validateCode)) {
            return new Result(false, "验证码错误，请重新输入");
        }
        Result result = null;
        try {
            result = orderService.order(map);
        } catch (Exception e) {
            //预约失败
            return result;
        }
        if (result.isFlag()) {
            //预约成功，发送成功短信
            String orderDate = (String) map.get("orderDate");
            try {
//                SMSUtils1.sendSms(SMSUtils1.VALIDATE_CODE,telephone,orderDate);
                System.out.println("预约成功");
            } catch (Exception e) {

            }
        }
        return result;
    }

    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            Map map = orderService.findById(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, map);
        } catch (Exception e) {
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);

        }
    }
}
